package com.yx.cloud.network.ap;

import com.yx.cloud.network.DataPacket;

/**
 * 0帧头（Header）	1	固定为0xAA
 * 1顺序（Index）	1	从1开始，用于分包发送
 * 2数据总包数（PackageSum）	1	整体数据的分包总数
 * 3数据长度（Length）	2	数据包的有效长度：Cmd+Data
 * 4命令字（Cmd）	1	控制指令
 * 数据（Data）	N
 * 检校和（CheckSum）	1	Cmd和Data数据域的所有数据累加和
 */
public class ApDataPacket extends DataPacket {
    public static final byte HEADER = (byte) 0xAA;
    public static int REAL_SIZE = 1024 - 7;

    //包数据详情
    public byte header = (byte) 0xAA;
    public byte order;
    public byte packageSum;
    public int length;
    public static final int CMD_START = 5;
    public byte cmd;
    public byte[] data;
    public byte checkSum;

    //单个分包的数据
    public byte[] packData;

    public ApDataPacket(byte[] packData) {
        this.packData = packData;

        this.header = packData[0];
        this.order = packData[1];
        this.packageSum = packData[2];
        this.length = convertTwoBytesToInt(packData[3], packData[4]);
        this.cmd = packData[5];
        this.data = new byte[length - 1];
        System.arraycopy(packData, 6, data, 0, data.length);
        this.checkSum = packData[0];
    }

    private static boolean checkData(byte[] packData) {
        int length = convertTwoBytesToInt(packData[3], packData[4]);
        byte checkSum = packData[CMD_START + length];

        byte sum = 0;

        for (int i = CMD_START; i < CMD_START + length; i++) {
            sum += packData[i];
        }

        return checkSum == sum;
    }

    public static boolean validateSlicePackage(byte[] packData) {
        if (packData == null) {
            //数据为空 抛弃
            return false;
        }
        int packLength = convertTwoBytesToInt(packData[3], packData[4]);
        if (packData.length < 7 || packLength < 1 || packData.length < (CMD_START + packLength + 1)) {
            //数据长度不对 抛弃
            return false;
        }

        if (packData[0] != (byte) 0xAA) {
            return false;
        }

        if (!checkData(packData)) {
            return false;
        }

        return true;
    }

    public static byte[] convertShortToTwoBytes(short value) {
        byte[] bytes = new byte[2];
        bytes[0] = (byte) ((value >> 8) & 0xff);
        bytes[1] = (byte) (value & 0xff);

        return bytes;
    }

    public static int convertTwoBytesToInt(byte b1, byte b2) {
        return (int) ((b1 << 8) | (b2 & 0xFF));
    }


    @Override
    public int getCmd() {
        return this.cmd;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    @Override
    public void setOrder(byte order) {
        this.order = (byte) order;
    }

    @Override
    public int getPacketSum() {
        return this.packageSum;
    }

    @Override
    public int getPacketLength() {
        return this.length;
    }

    @Override
    public byte[] getContentData() {
        return this.data;
    }
}
